package com.game.NioSocket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;

import org.apache.log4j.Logger;

import com.commons.DBPool.DBManager;






/***
 * 并发控制
 * 排队处理
 * 分发线程
 * @author chenlei
 *
 */
public class Gserver extends Thread{
	public  Logger logger=Logger.getLogger(Gserver.class.getClass());
	private ServerSocketChannel serverchannel;
	
	private SocketChannel channel;
	
	private LinkedList<dispatcher> managerThread=new LinkedList<dispatcher>();//线程分发队列
	
	private int pointDispatcher=0;//managerThread指针
	
	public Gserver(){
		try {
			serverchannel=ServerSocketChannel.open();
			//set non-blocking in case of the accept method will be return null
			serverchannel.configureBlocking(true);
			serverchannel.socket().bind(new InetSocketAddress(DBManager.Port));
			logger.info("server is liseting the port: "+DBManager.Port);
			this.start();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 *  线程分发器
	 * @param size
	 */
	public void creatThread(byte size){
		for(byte i=0;i<size;i++){
			dispatcher dis=new dispatcher();
			Thread t=new Thread(dis);
			t.setName("线程分发管理器");
			t.setDaemon(false);
			t.start();
			managerThread.add(dis);
		}
	}
	
	/**
	 * 获取可用的 dispatcher
	 * @return dispatcher
	 */
	public dispatcher getnext(){
		dispatcher dis=null;
		pointDispatcher++;
		if(pointDispatcher>=managerThread.size()){
			pointDispatcher=0;
		}
		dis=managerThread.get(pointDispatcher);
		return dis;
	}
	
	public void run(){
		creatThread(DBManager.ThreadMax);
		while(DBManager.isRunning){
			try {
				//If this channel is in non-blocking mode then this method will immediately return null ;
				channel=serverchannel.accept();
				logger.info(channel.socket().getRemoteSocketAddress()+"wait to connect the server");
				getnext().RegisterChannel(new Gsocket(channel));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	/***
	 * 出现异常  关闭通道
	 */
	public void shutdown(){
		
	}
	
}
